package com.xuecheng.content.controller;

import com.xuecheng.api.content.FileManagerControllerApi;
import com.xuecheng.api.content.model.dto.UploadTokenResult;
import com.xuecheng.common.util.RandomStringUtil;
import org.apache.commons.lang.RandomStringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * @author wuyunyun
 * @data 2021/10/11 16:29
 */
@RestController
public class FileManagerController implements FileManagerControllerApi {

    @Autowired
    private RestTemplate restTemplate;

    /*
   * #文件系统微服的请求地址
       file.service.url=http://127.0.0.1:56082/farming/generatetoken?origin=qiniu
       #文件存储空间名称
       file.service.bucket= xc127-static-imgs
       #文件存储区域的地址
       file.service.upload.region = http://upload.qiniu.com
       #文件访问的cdn加速域名
       cdn.domain = qxi0nnrr8.hd-bkt.clouddn.com
   * */
    @Value("${file.service.url}")
    private String url;
    @Value("${file.service.bucket}")
    private String bucketName;
    @Value("${file.service.upload.region}")
    private String region;
    @Value("${cdn.domain}")
    private String domain;
    @Value("${file.service.tokenType}")
    private String tokenType;



    @GetMapping("/common/qnUploadToken")
    public UploadTokenResult qiniuUploadToken() {
        Map<String, Object> bodyMap = new HashMap<>();
        bodyMap.put("tokenType",tokenType);
        bodyMap.put("scope",bucketName);
        bodyMap.put("deadline",3600);
        String key = UUID.randomUUID().toString()+ RandomStringUtils.randomAlphanumeric(16);
        bodyMap.put("key",key);
        ResponseEntity<HashMap> resultMap = restTemplate.postForEntity(url, bodyMap, HashMap.class);
        String resultToken =(String) resultMap.getBody().get("result");
        UploadTokenResult result= new UploadTokenResult();
        result.setQnToken(resultToken);
        result.setDeadline(3600L);
        result.setDomain(domain);
        result.setKey(key);
        result.setScope(bucketName);
        result.setUp_region(region);
        result.setTokenType(tokenType);
        return result;
    }
}
